<template>
  <view class="search-container">
    <div class="loading-container" v-show="loading">
      <u-loading mode="circle" show />
    </div>
    <!-- 搜索条件 -->
    <view class="search-hd" @touchmove.stop.prevent>
      <u-form
        id="myForm"
        :model="form"
        :border-bottom="false"
        label-position="left"
        label-align="center"
        :label-width="160" 
        :label-style="labelStyle" 
        ref="uForm"
        :style="`height: ${isFilterShowMore ? 'auto' : '280rpx'}`"
      >
        <u-form-item label="筛 选" class="my-form-item">
          <u-input class="my-input-rp02name" v-model="form.province" :height="98" type="select" placeholder="省"
            :select-open="show" @tap="handleSelectProvince()" />
          <u-input class="my-input-rp03name" v-model="form.city" :height="98" type="select" placeholder="市"
            :select-open="showCity" @tap="handleSelectCity()" />
          <u-input class="my-input-brand" v-model="form.area" :height="98" type="select" placeholder="区"
            :select-open="showArea" @tap="handleAreaSelect()" />
        </u-form-item>
        <u-form-item label="创建人" class="my-form-item">
          <input class="my-input-storeAddress" style="height: 98rpx;" v-model="form.createBy" type="text"
            placeholder="请输入" @input="debounceSearch">
        </u-form-item>
        <u-form-item label="品牌名称" class="my-form-item">
          <input class="my-input-storeAddress" style="height: 98rpx;" v-model="form.brand" type="text"
            placeholder="请输入" clearable @input="debounceSearch">
        </u-form-item>
        <u-form-item label="市场名称" class="my-form-item">
          <input class="my-input-storeAddress" style="height: 98rpx;" v-model="form.marketName" type="text"
            placeholder="请输入" clearable @input="debounceSearch">
        </u-form-item>
      </u-form>
      <view class="show-more" @tap="isFilterShowMore = !isFilterShowMore">
        <text style="margin-right: 12rpx">{{ isFilterShowMore ? '收起' : '展开' }}</text>
        <u-icon size="24rpx" :name="isFilterShowMore ? 'arrow-up' : 'arrow-down'"></u-icon>
      </view>
      <!-- tab -->
      <view class="data-tabs">
        <u-tabs 
          :list="tabOpts" 
          :gutter="20" 
          :current="currentTab" 
          :height="100"
          :bar-style="{ bottom: '20rpx' }" 
          @change="handleTabChange"
        ></u-tabs>
      </view>
      <view class="shortcut-filter">
        <u-checkbox v-model="form.onlyMe" @change="doQuery">只看我的</u-checkbox>
      </view>
    </view>
    <!-- 搜索结果 -->
    <view class="store-rcord-list">
      <scroll-view v-if="storeList.length > 0" class="content" scroll-y style="width: 100%;height: 100%;"
        :scroll-top="scrollTop" @scroll="e => currentScrollTop = e.detail.scrollTop">
        <!--  -->
        <view v-for="item in storeList" class="rcord-item" @click="goOrderDetail(item)" :key="item.id">
          <view class="rcord-item-user">
            <view class="user-info">
              <image :src="item.custAvatar || '../../static/default_user_icon.jpg'"></image>
              {{ item.custName }}
            </view>
            <view class="top-right">
              <view class="top-right__status" :style="{ color: getColorByStatus(item.status) }">{{ item.status |
                statusFilter }}</view>
              <template v-if="item.overdue && item.status === '1'">
                <view class="top-right__divider"></view>
                <view class="top-right__delay">已超期</view>
              </template>
            </view>
          </view>
          <view class="rcord-item-describe" style="justify-content: space-between;align-items: flex-end;">
            <view style="flex: 1;display: flex;align-items: flex-start;">
              <view class="label">销区：</view>
              <view class="contents">
                {{ item.province ? `[${item.province}]` : '[无省份]' }}
                {{ item.city ? `[${item.city}]` : '[无城市]' }}
                {{ item.area ? `[${item.area}]` : '[无区县]' }}
              </view>
            </view>
          </view>
          <view class="rcord-item-describe" style="justify-content: space-between;">
            <view style="flex: 1;display: flex;align-items: flex-start;">
              <view class="label">品牌：</view>
              <view class="contents">{{ item.brand }}</view>
            </view>
          </view>
          <view class="rcord-item-describe" style="justify-content: space-between;">
            <view style="flex: 1;display: flex;align-items: flex-start">
              <view class="label">市场名称：</view>
              <view class="contents">{{ item.marketName }}</view>
            </view>
          </view>
          <view class="rcord-item-describe" style="align-items: flex-start;" v-if="item.status === '4' && item.storeName">
            <view class="label">店面：</view>
            <view class="contents" style="line-height: 1.8;">{{ item.storeName }}</view>
          </view>
          <view class="rcord-item-describe">
            <view class="label">创建时间：</view>
            <view class="contents">{{ item.createTime }}</view>
          </view>
          <!-- 启动 -->
          <view class="rcord-item-describe" v-if="item.status === '1'">
            <view class="label">启动时间：</view>
            <view class="contents">{{ item.startTime }}</view>
          </view>
          <view class="rcord-item-describe" v-if="item.status === '1'">
            <view class="label">预计完成时间：</view>
            <view class="contents">{{ item.investPlanCompletionTime }}</view>
          </view>
          <!-- 已完成 -->
          <view class="rcord-item-describe" v-if="item.status === '4'">
            <view class="label">完成时间：</view>
            <view class="contents">{{ item.completionTime }}</view>
          </view>
          <!-- 已关闭 -->
          <view class="rcord-item-describe" v-if="item.status === '3'">
            <view class="label">关闭时间：</view>
            <view class="contents">{{ item.closingTime }}</view>
          </view>
          <view class="rcord-item-describe" v-if="item.status === '3'">
            <view class="label">关闭原因：</view>
            <view class="contents">{{ item.shutdownReason  }}{{ item.otherShutdownReason ? `(${item.otherShutdownReason})` : '' }}</view>
          </view>
        </view>
        <u-loadmore :status="loadMoreStatus" @loadmore="handleLoadMore" :load-text="loadText"
          :bg-color="loadMoreStatus !== 'loading' ? '#F4F5F7' : '#fff'"
          :style="`height: 88rpx;background: ${loadMoreStatus !== 'loading' ? '#F4F5F7' : '#fff'};`" />
      </scroll-view>
      <!-- 暂无数据 -->
      <view v-if="storeList.length == 0" class="none-record">暂无记录</view>
    </view>
    <!-- 新建 -->
    <view class="footer-container">
      <u-button class="footer-btn" shape="circle" @click="goCreateStore" type="primary">新建</u-button>
    </view>
    <!-- 筛选弹出框 -->
    <u-picker mode="selector" class="my-u-picker" v-model="show" @confirm="handleProvinceChange" :range="provinceOpts"
      :z-index="9999" range-key="text" />
    <u-picker mode="selector" class="my-u-picker" v-model="showCity" @confirm="handleCityChange" :range="cityOpts"
      :z-index="9999" range-key="text" />
    <u-picker mode="selector" class="my-u-picker" v-model="showArea" @confirm="handleAreaChange" :range="areaOpts"
      :z-index="9999" range-key="text" />
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import {
  provinceList,
  getBranchInverstList,
  getBranchInverstListCount,
  getAllRegionByParentId
} from '../../common/service.js'
import uFormItem from '../../uview-ui/components/u-form-item/u-form-item.vue'
const tabOpts = [{
  name: '全部',
  value: undefined,
  countKey: 'allCount',
},
{
  name: '新建',
  value: '0',
  countKey: 'newCount',
},
{
  name: '已启动',
  value: '1',
  countKey: 'startCount',
},
{
  name: '已完成',
  value: '4',
  countKey: 'completeCount',
},
{
  name: '已超期',
  value: '2',
  countKey: 'overdueCount',
},
{
  name: '已关闭',
  value: '3',
  countKey: 'closeCount',
},
]
const defaultOpts = [{ text: '全部', value: '全部' }];
export default {
  components: { uFormItem },
  data() {
    return {
      labelStyle: {
        'height': '98rpx',
        'color': '#666666',
        'font-size': '28rpx',
        'font-family': 'PingFangSC-Regular, PingFang SC',
        'font-weight': '400',
        'display': 'flex',
        'justify-content': 'space-between'
      },
      form: {
        provice: '',
        city: '',
        area: '',
        brand: '',
        marketName: '',
        onlyMe: false,
        createBy: '',
      },
      show: false,
      showCity: false,
      showArea: false,
      provinceOpts: [],
      cityOpts: [],
      areaOpts: [],
      storeList: [],
      nearStoreList: [],
      tempValue: '',
      tabOpts,
      currentTab: 0,
      loading: false,
      pageNo: 1,
      pageSize: 10,
      loadMoreStatus: 'loadmore',
      scrollTop: 0,
      currentScrollTop: 0,
      loadText: {
        loadmore: '点击加载更多',
        loading: '努力加载中',
        nomore: '暂无更多数据'
      },
      isFilterShowMore: false,
    }
  },
  filters: {
    statusFilter(v) {
      return {
        0: '新建',
        1: '已启动',
        2: '已超期',
        3: '已关闭',
        4: '已完成',
      }[v] || '未知'
    }
  },
  onLoad: function (option) {
    this.stop()
    // this.doQuery()
  },
  onShow() {
    this.queryData();
  },
  methods: {
    // 阻止页面滚动
    stop() {
      var box = function (e) {
        passive: false;
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener("touchmove", box, false);
    },
    // 允许页面滚动
    move() {
      var box = function (e) {
        passive: false
      };
      document.body.style.overflow = ''; // 出现滚动条
      document.removeEventListener("touchmove", box, false);
    },
    // Tab变动
    handleTabChange(val) {
      console.log('handleTabChange', val)
      this.currentTab = val;
      this.doQuery();
    },
    getFilterParams() {
      const { province, city, area } = this.form;
      const params = { 
        ...this.form, 
        province: province === '全部' ? undefined : province,
        city: city === '全部' ? undefined : city,
        area: area === '全部' ? undefined : area,
        onlyMe: undefined 
      };
      if (this.form.onlyMe) {
        params.createBy = this.CONFIG.user.name;
      }
      return params;
    },
    queryTabCount(params) {
      const that = this;
      getBranchInverstListCount(params, function (resuser) {
        if (resuser && resuser.statusCode == 200) {
          const { data = {} } = resuser.data;
          that.tabOpts = tabOpts.map(opt => {
            const num = data[opt.countKey] || 0;
            return {
              ...opt,
              name: `${opt.name}(${num})`
            }
          })
        }
      })
    },
    // 筛选条件后查询的列表数据
    queryData() {
      const that = this;
      const pageNo = this.pageNo;
      const filterParams = this.getFilterParams();
      const params = {
        ...filterParams,
        pageNum: pageNo,
        pageSize: this.pageSize,
      };
      if (this.currentTab > 0) {
        params.status = tabOpts[this.currentTab].value;
      }
      this.tempValue = that.form.storeName ? that.form.storeName : ''
      this.loading = true;
      this.loadMoreStatus = 'loading';
      this.queryTabCount(filterParams);
      getBranchInverstList(params, function (resuser) {
        that.loading = false;
        if (resuser && resuser.statusCode == 200) {
          that.loadMoreStatus = 'loadmore';
          const rs = resuser.data;
          if (rs.code == 200) {
            const { rows = [], total } = rs;
            that.storeList = pageNo === 1 ? rows : [...that.storeList, ...rows];
            if (that.storeList.length >= total) {
              that.loadMoreStatus = 'nomore';
            }
          } else {
            if (rs.msg) {
              that.$refs.uToast.show({
                title: rs.msg || '获取待办列表失败',
                type: 'error',
                duration: 3000,
                callback: function () {
                  return;
                }
              });
            }
          }
        } else {
          console.log('模拟数据')
        }
      }, function (e) {
        that.loadMoreStatus = 'loadmore';
        that.loading = false;
      });
    },
    handleLoadMore() {
      if (this.loading) return;
      this.pageNo++;
      this.queryData();
    },
    // 下拉刷新被触发
    doQuery() {
      this.pageNo = 1;
      this.scrollTop = this.currentScrollTop;
      this.$nextTick(() => {
        this.scrollTop = 0
      });
      this.queryData();
    },
    getColorByStatus(status) {
      return {
        0: '#007AFF',
        1: '#FA8C16',
        2: '#FA8C16',
        3: '#666666',
        4: '#1DC883',
      }[status] || '#007AFF'
    },
    // 获取用户id
    getCode: function () {
      return this.CONFIG.user.id;
    },
    debounceSearch() {
      this.$u.debounce(this.queryData, 500);
    },
    // 获取省市区拓扑数据
    fetchTopologyData(parentId) {
      return new Promise((resolve, reject) => {
        getAllRegionByParentId(
          parentId,
          (result) => {
            if (result && result.statusCode == 200) {
              const { data: rs } = result;
              if (rs.code == 200) {
                resolve(
                  (rs.data || []).map((item) => ({
                    text: item.regionName,
                    value: item.id,
                  }))
                );
              } else {
                this.$refs.uToast.show({
                  title: rs.msg || rs.errMsg || "获取省市区数据失败",
                  type: "error",
                  duration: 3000,
                });
                reject(rs.msg);
              }
            }
          },
          (e) => {
            this.$refs.uToast.show({
              title: e || "获取省市区数据失败",
              type: "error",
              duration: 3000,
            });
            reject(e);
          }
        );
      });
    },
    async fetchProvinceOpts() {
      const data = await this.fetchTopologyData('1');
      this.provinceOpts = [...defaultOpts, ...data];
      return data;
    },
    // 点击省份筛选
    async handleSelectProvince() {
      if (this.provinceOpts.length > 0) {
        this.show = true;
        return;
      }
      await this.fetchProvinceOpts();
      this.show = true;
    },

    // 点击城市
    handleProvinceChange(e) {
      const index = e[0];
      const opt = this.provinceOpts[index];
      if (!opt) return;
      const { text: value, value: id } = opt;
      this.form = {
        ...this.form,
        province: value,
        city: '',
        area: '',
      }
      // 重置后续选项数据
      this.cityOpts = [...defaultOpts];
      this.areaOpts = [...defaultOpts];
      // 查询列表数据
      this.queryData();
      if (value !== '全部') {
        this.handleSelectCity(id);
      }
    },

    async fetchCityOpts(provinceId) {
      const data = await this.fetchTopologyData(provinceId);
      this.cityOpts = [...defaultOpts, ...data];
      return data;
    },
    // 点击市
    async handleSelectCity(provinceId) {
      if (!this.form.province) {
        this.$refs.uToast.show({
          title: '请先选择省份',
          type: 'warning',
          duration: 3000,
        });
        return;
      }
      if (this.cityOpts.length > 1) {
        this.showCity = true;
      } else {
        await this.fetchCityOpts(provinceId);
        this.showCity = true;
      }
    },
    // 点击城市回调
    handleCityChange(e) {
      if (!this.cityOpts || this.cityOpts.length === 0) return;
      const index = e[0];
      const opt =  this.cityOpts[index];
      if (!opt) return;
      const { text: value, value: id } = opt;
      this.form.city = value;
      this.form.area = '';
      // 重置后续选项数据
      this.areaOpts = [...defaultOpts];
      // 请求
      if (value !== '全部') {
        this.handleAreaSelect(id)
      }
      this.queryData()
    },
    async fetchAreaOpts(cityId) {
      const data = await this.fetchTopologyData(cityId);
      this.areaOpts = [...defaultOpts, ...data];
      return data;
    },
    // 点击区域名称
    async handleAreaSelect(cityId) {
      if (!this.form.city) {
        this.$refs.uToast.show({
          title: '请先选择城市',
          type: 'warning',
          duration: 3000,
        });
        return;
      }
      if (this.areaOpts.length > 1) {
        this.showArea = true;
      } else {
        await this.fetchAreaOpts(cityId);
        this.showArea = true;
      }
    },
    // 点击品牌名称回调
    handleAreaChange(e) {
      const index = e[0];
      const opt =  this.areaOpts[index];
      if (!opt) return;
      this.form.area = opt.text;
      // 查询门店列表
      this.queryData();
    },

    // 助店详情
    goOrderDetail(item) {
      uni.navigateTo({
        url: `./detail?id=${item.id}`
      });
    },
    goCreateStore() {
      uni.navigateTo({
        url: './create'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
page,
.search-container {
  background-color: #F3F5F7;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.search-hd {
  // position: fixed;
  // left: 0;
  // top: 20rpx;
  // width: 750rpx;
  // height: 500rpx;
  background: #F4F5F7;
  border-radius: 30rpx 30rpx 0px 0px;
}

.data-tabs {
  padding: 30rpx 20rpx;
  padding-right: 0;
  background: #F3F5F7;
  .u-tabs {
    border-radius: 16rpx;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  z-index: 1;
  opacity: 0.8;
}

#myForm {
  width: 100%;
  padding-bottom: 20rpx;
  background: #fff;
  overflow: hidden;
}

.my-form-item {
  padding: 13rpx 0;
}

.my-form-item:first-child {
  padding-top: 30rpx;
  margin-top: 20rpx;
}

.show-more {
  padding: 10rpx 0 20rpx 0;
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: center;
  color: #007AFF;
  font-size: 28rpx;
  background: #fff;
  // z-index: 1;
  position: relative;
}

.my-input-rp02name {
  width: 150rpx;
  height: 98rpx;
  background: #F7F7F7;
  border-radius: 16rpx;
  padding-left: 15rpx !important;
  padding-right: 15rpx !important;
}

.my-input-rp03name,
.my-input-brand {
  width: 150rpx;
  height: 98rpx;
  background: #F7F7F7;
  border-radius: 16rpx;
  margin-left: 10rpx;
  padding-left: 15rpx !important;
  padding-right: 15rpx !important;
}

.shortcut-filter {
  padding: 0 20rpx 20rpx 30rpx;
}

.my-input-brand {
  margin-right: 30rpx;
}

.my-input-storeAddress {
  width: 540rpx;
  height: 98rpx;
  background: #F7F7F7;
  border-radius: 16rpx;
  padding-left: 15rpx !important;
  padding-right: 15rpx !important;
  margin-right: 30rpx;
}

.my-u-picker {
  position: fixed;
  z-index: 99 !important;
}

/* 列表数据 */
.store-rcord-list {
  padding: 0 20rpx;
  flex: 1;
  overflow: hidden;

  .rcord-item {
    width: 710rpx;
    padding: 20rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    margin-bottom: 20rpx;

    &-user {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25rpx;

      .user-info {
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 32rpx;
        color: #000000;
        display: flex;
        align-items: center;

        image {
          width: 60rpx;
          height: 60rpx;
          border-radius: 30rpx;
          margin-right: 20rpx;
        }
      }

      .top-right {
        display: flex;
        flex: 1;
        justify-content: flex-end;
        font-size: 30rpx;
        font-weight: 600;

        &__status {
          padding-right: 10rpx;
        }

        &__divider {
          height: 24rpx;
          width: 2rpx;
          margin-top: 12rpx;
          background-color: #D9D9D9;
        }

        &__delay {
          color: #FF4848;
          padding-left: 10rpx;
        }
      }

      .time {
        margin-left: 16rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
      }
    }

    &-describe {
      padding: 4rpx 0;
      display: flex;
      // align-items: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #333333;
      .label {
        color: #999999;
        min-width: 90rpx;
      }

      .contents {
        flex: 1;
        // white-space:nowrap;
        // text-overflow:ellipsis;
        // overflow:hidden; 
      }

      .subtext {
        flex: 1;
      }
    }
  }
}

.footer-container {
  padding: 15rpx 25rpx 30rpx 30rpx;
  background: #fff;
}

.none-record {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 32rpx;
  color: #999999;
  padding-top: 534rpx;
  background: url('../../static/toStore/storeRcord-none.png') no-repeat center 213rpx;
  background-size: 460rpx 319rpx;
  text-align: center;
}
</style>